package com.zjw.jdbc.util;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;

import javax.sql.DataSource;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import net.sourceforge.groboutils.junit.v1.TestRunnable;

/**
 * test thread request for connections
 * @author zjw
 *
 */
public class RequestForConnectionRunner extends TestRunnable {
	
	private DataSource dataSource;
	private long sleepMillis = 300;

	public RequestForConnectionRunner(DataSource dataSource) {
		this.dataSource = dataSource;
	}
	
	public void setSleepMillis(long sleepMillis){
		this.sleepMillis = sleepMillis;
	}

	@Override
	public void runTest() throws Throwable {
		Connection conn = null;
		for(int i=0;i<20;i++){
			try {
				conn = dataSource.getConnection();
				if(dataSource instanceof ComboPooledDataSource){
					ComboPooledDataSource cpds = (ComboPooledDataSource) dataSource;
					System.err.println("numConnectionDefaultUser: "
							+ cpds.getNumConnectionsDefaultUser()
							+ ",numBusyConnectionDefaultUser: "
							+ cpds.getNumBusyConnectionsDefaultUser()
							+ ",numIdleConnectionDefaultUser: "
							+ cpds.getNumIdleConnectionsDefaultUser());
//					System.err.println("numBusyConnectionDefaultUser: " + cpds.getNumBusyConnectionsDefaultUser());
//					System.err.println("numIdleConnectionDefaultUser: " + cpds.getNumIdleConnectionsDefaultUser());
				}
				System.out.println(Thread.currentThread().getName() + "-->conn["+i+"] : " + conn.hashCode());
//				Thread.sleep(sleepMillis);
				selectSome(conn);
//				System.out.println("conn.isClosed? " + conn.isClosed());
			} catch (SQLException e) {
				e.printStackTrace();
			} /*catch (InterruptedException e) {
				e.printStackTrace();
			}*/
		}

	}
	
	private void selectSome(Connection conn){
		
		PreparedStatement ps = null;
		ResultSet rs = null;
		String sql = "SELECT * FROM t_user WHERE id = ?";
		try {
			ps = conn.prepareStatement(sql);
			ps.setInt(1, 21);
			rs = ps.executeQuery();
			if(rs.next()){
				String username = rs.getString("username");
				String password = rs.getString("password");
				Date createTime = rs.getDate("create_time");
				System.out.println("username=["+username+"],password=["+password+"],create_time=["+createTime+"]");
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally{
			JdbcUtil.releaseDB(rs, ps, conn);
		}
	}

}







